package pa1.chat.server;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;

import pa1.chat.client.ChatClient;


public class ChatServerImpl extends UnicastRemoteObject implements ChatServer{

	/**
	 * 
	 */
	private static final long serialVersionUID = -3036897469433970919L;
	private static final int DefaultPort = 1099;
	private ArrayList<ChatClient> clients;
	protected ChatServerImpl() throws RemoteException {
		super();
		clients = new ArrayList<ChatClient>();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//establish the registry
		Registry reg = null;
		try {
			reg = LocateRegistry.createRegistry(DefaultPort);
		} catch (RemoteException e) {
			try{
				reg = LocateRegistry.getRegistry();
			} catch(RemoteException e2){
				System.out.println("Registry couldn't be established: " + e2.getMessage());
			}
		}
		System.out.println("Registry established");
		
		try {
			ChatServer chatServer = new ChatServerImpl();
			reg.rebind(ChatServer.SERVICE_NAME, chatServer);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		
		

	}

	@Override
	public void register(ChatClient client) throws RemoteException {
		String clientName = client.getName();
		synchronized(clients){
			clients.add(client);
			for(ChatClient c : clients){
				try{
					c.displayMessage(clientName + " has joined.");
				}catch(RemoteException e){
					
				}
			}
		}
	}

	@Override
	public void unregister(ChatClient client) throws RemoteException {
		String clientName = client.getName();
		synchronized(clients){
			clients.remove(client);
			for(ChatClient c : clients){
				try{
					c.displayMessage(clientName + " has left.");
				}catch(RemoteException e){
					
				}
				
			}
		}	
	}

	@Override
	public void sendMessage(ChatClient client, String message)
			throws RemoteException {
		String clientName = client.getName();
		synchronized(clients){
			for(ChatClient c : clients){
				try{
					c.displayMessage(clientName + ": " + message);
				}catch(RemoteException e){
					
				}
				
			}
		}		
	}
	
	/*
	protected synchronized void forwardMessage(String message){
		for(ChatClient client : clients){
			try{
				client.displayMessage(message);
			}catch(RemoteException re){
				
			}
		}
	}*/

}
